package com.gitee.wsl.ext.array

/**
 * Safely iterates over an array, catching exceptions for each element.
 *
 * This function iterates over the elements of the array, executing the [block] for each element.
 * If an exception is thrown during the execution of the block,
 * the [onException] handler is called with the element and the exception.
 *
 * @param T The type of elements in the array.
 * @param onException A function that handles exceptions thrown during the execution of the block.
 * It receives the element and the exception as parameters.
 * @param block The function to be executed for each element.
 */
inline fun <T> Array<T>.forEachSafe(onException: (Exception, T) -> Unit = { _, _ -> }, block: (T) -> Unit) {
    forEach {
        try {
            block(it)
        } catch (e: Exception) {
            onException(e, it)
        }
    }
}


/**
 * Safely iterates over an array, catching exceptions for each element.
 *
 * This function iterates over the elements of the array, executing the [block] for each element.
 * If an exception is thrown during the execution of the block,
 * the [onException] handler is called with the element and the exception.
 *
 * @param T The type of elements in the array.
 * @param onException A function that handles exceptions thrown during the execution of the block.
 * It receives the element and the exception as parameters.
 * @param block The function to be executed for each element.
 */
inline fun <T> Array<T>.forEachSafe(onException: (Exception) -> Unit = {}, block: (T) -> Unit) {
    forEach {
        try {
            block(it)
        } catch (e: Exception) {
            onException(e)
        }
    }
}
